<?php
declare (strict_types = 1);

namespace app\event;

use Symfony\Contracts\EventDispatcher\Event;
use app\model\AdminActionLog;
use think\facade\Session;
use think\Request;

class AdminActionEvent extends Event
{
    // 事件名
    const EVENT_NAME = "admin.action_log";

    public function __construct(Request $request, $data)
    {
        // todo
        //dump(__CLASS__);
        $this->handle($request, $data);
    }

    // 切换请求
    public function handle(Request $request, $data)
    {
        $uri    = $request->baseUrl();
        $ip     = $request->ip();
        $remark = $data;
        if (is_array($data)) $remark = json_encode($data, JSON_UNESCAPED_UNICODE);
        $remark = substr($remark, 0, 1000);

        switch(strtolower($request->method())){
            case 'get':
                $this->onGetRequest($uri, $ip, $remark);
                break;
            case 'post':
                $this->onPostRequest($uri, $ip, $remark);
                break;
            case 'put':
                $this->onPutRequest($uri, $ip, $remark);
                break;
            case 'delete':
                $this->onDeleteRequest($uri, $ip, $remark);
                break;
            default:
                // nothing todo
        }
    }// handle() end

    // 访问
    public function onGetRequest(string $uri, string $ip, string $remark)
    {
        $this->generateLog($uri, $ip, $remark);
    }// onGetRequest() end

    // 保存
    public function onPostRequest(string $uri, string $ip, string $remark)
    {
        $this->generateLog($uri, $ip, $remark);
    }// onPostRequest() end

    // 更新
    public function onPutRequest(string $uri, string $ip, string $remark)
    {
        $this->generateLog($uri, $ip, $remark);
    }// onPutRequest() end

    // 删除
    public function onDeleteRequest(string $uri, string $ip, string $remark)
    {
        $this->generateLog($uri, $ip, $remark);
    }// onDeleteRequest() end

    // 写入日志
    public function generateLog(string $uri, string $ip, string $remark)
    {
        AdminActionLog::generateLog(Session::get('admin_user.id', 0), $uri, $ip, $remark);
    }// generateLog() end
}
